package com.lhn.netty.netty_demo.heartbeat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lhn
 * @date 2025/06/03 21:24
 * @since 1.0.0
 **/
public class MyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 触发用户事件
     * @param ctx 上下文
     * @param evt 事件
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            //将  evt 向下转型 IdleStateEvent
            IdleStateEvent event = (IdleStateEvent) evt;
            String eventType = null;
            switch (event.state()) {
                case READER_IDLE:
                    eventType = "读空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写空闲";
                    break;
                default:
                    eventType = null;
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            System.out.println("服务器做相应处理.." + sdf.format(new Date()));
            System.out.println(ctx.channel().remoteAddress() + "--超时时间--" + eventType);
            System.out.println("服务器做相应处理.." + sdf.format(new Date()));
            //如果发生空闲，我们关闭通道
            Channel channel = ctx.channel();
            String channelId = channel.id().asLongText();
            System.out.println("空闲id====" + channelId);
            channel.close();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}